package com.wyj.controller;

import com.alibaba.fastjson.JSONObject;
import com.wyj.pojo.Message;
import com.wyj.pojo.Page;
import com.wyj.pojo.User;
import com.wyj.service.imp.MessageServiceImp;
import com.wyj.service.imp.UserServiceImp;
import com.wyj.util.CommunityConstant;
import com.wyj.util.CommunityUtil;
import com.wyj.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/7/19
 */
@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    MessageServiceImp messageServiceImp;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    UserServiceImp userServiceImp;

    //朋友的私信列表
    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public String getMessage(Model model, Page page) {


        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/getMessage");
        page.setRows(messageServiceImp.getConversationCount(user.getId()));

        //该用户跟所有聊天者的最新信息
        List<Message> conversationList = messageServiceImp.getConversations(user.getId(), page.getOffset(), page.getLimit());

        List<Map<String, Object>> conversations = new ArrayList<>();

        if (conversationList != null) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                //保存和某个聊天者的最新信息
                map.put("message", message);
                //保存和某个聊天者的的未读信息
                map.put("unreadCount", messageServiceImp.getLetterUnreadCount(user.getId(), message.getConversationId()));
                //该聊天的有多少条信息
                map.put("messageCount", messageServiceImp.getLetterCount(message.getConversationId()));

                //获取聊天者的信息
                User target = user.getId() == message.getFromId() ? userServiceImp.getUserById(message.getToId()) : userServiceImp.getUserById(message.getFromId());
                map.put("target", target);

                conversations.add(map);
            }
        }

        model.addAttribute("conversations", conversations);

        //获取用户未读私信的总数量
        int letterUnreadCount = messageServiceImp.getLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        //将系统未读取信息数量统计其中
        int unreadSystemCounts = messageServiceImp.AllUnReadMessages(user.getId())
                - letterUnreadCount;

        model.addAttribute("unreadSystem",unreadSystemCounts);

        return "/site/letter";
    }

    //具体的某个人的私信
    @RequestMapping(value = "/getMessageDetail/{conversationId}", method = RequestMethod.GET)
    public String getMessageDetail(@PathVariable("conversationId") String conversationId, Model model, Page page) {

        int fromId = -1;
        int toId = -1;

        User user = hostHolder.getUser();

        page.setLimit(5);
        page.setPath("/getMessageDetail/" + conversationId);
        page.setRows(messageServiceImp.getLetterCount(conversationId));

        //该用户和某个聊天者的所有信息
        List<Message> letterList = messageServiceImp.getLetters(conversationId, page.getOffset(), page.getLimit());

        List<Map<String, Object>> letters = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                //一条私信的具体信息
                map.put("letter", message);
                //发送者的信息
                map.put("fromIdUser", userServiceImp.getUserById(message.getFromId()));
                letters.add(map);

                fromId = message.getFromId();
                toId = message.getToId();
            }
        }

        model.addAttribute("letters", letters);

        //存该聊天者的信息
        int targetId = user.getId() == fromId ? toId : fromId;
        model.addAttribute("target", userServiceImp.getUserById(targetId));

        //更改信息的状态  将status = 0 更改为1
        List<Integer> ids = getUpdateStatusIds(letterList);
        if (ids.size() != 0) {
            messageServiceImp.updateStatus(ids);
        }


        return "/site/letter-detail";
    }

    //发送私信  走一个异步请求
    @RequestMapping(value = "/addMessage", method = RequestMethod.POST)
    @ResponseBody
    public String sendMessage(String toName, String content) {
//        Integer.valueOf("abc");
        User userFrom = hostHolder.getUser();
        if (userFrom == null) {
            return CommunityUtil.getJsonString(1, "参数为空");
        }

        Message message = new Message();
        User userTo = userServiceImp.getUserByUsername(toName);

        message.setFromId(userFrom.getId());
        message.setToId(userTo.getId());

        if (userFrom.getId() > userTo.getId()) {
            message.setConversationId(String.valueOf(userTo.getId()) + "_" + String.valueOf(userFrom.getId()));
        } else {
            message.setConversationId(String.valueOf(userFrom.getId()) + "_" + String.valueOf(userTo.getId()));
        }

        message.setCreateTime(new Date());
        message.setContent(content);
        message.setStatus(0);//发送的消息表示未读

        messageServiceImp.addLetter(message);

        return CommunityUtil.getJsonString(0, "发送成功");
    }

    /**
     * @param
     * @Description:更改信息的状态
     * @retuen java.util.List<java.lang.Integer>
     * @author wyj
     * @since 2022/7/23 10:31
     */
    private List<Integer> getUpdateStatusIds(List<Message> messages) {

        List<Integer> list = new ArrayList<>();

        if (messages != null) {
            for (Message message : messages) {
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    list.add(message.getId());
                }
            }
        }
        return list;
    }

    /**
     * @param
     * @Description 处理系统通知中的三个主题的信息的概览  点赞  关注  评论
     * @retuen
     * @author wyj
     * @since 2022/8/20 15:52
     */
    @RequestMapping(value = "/getNoticeList", method = RequestMethod.GET)
    public String getNoticeList(Model model) {
        User user = hostHolder.getUser();

        //处理评论
        Message messageComment = messageServiceImp.selectLatestNotice(user.getId(), TOPIC_COMMENT);

        Map<String, Object> mapComment = new HashMap<>();
        if (messageComment != null) {

            mapComment.put("message",messageComment);

            //将message中的content的中的JSONString形式 获取出来
            String content = HtmlUtils.htmlUnescape(messageComment.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            mapComment.put("user",userServiceImp.getUserById((int)data.get("userId")));
            mapComment.put("entityType",data.get("entityType"));
            mapComment.put("entityId",data.get("entityId"));
            mapComment.put("postId",data.get("postId"));

            int countsNotices = messageServiceImp.selectCountsNotices(user.getId(), TOPIC_COMMENT);
            int noReadNotices = messageServiceImp.selectCountsNoReadNotices(user.getId(), TOPIC_COMMENT);

            mapComment.put("countsNotices",(Integer)countsNotices);
            mapComment.put("noReadNotices",(Integer)noReadNotices);

        }



        //处理点赞
        Message messageLike = messageServiceImp.selectLatestNotice(user.getId(), TOPIC_LIKE);

        Map<String, Object> mapLike = new HashMap<>();
        if (messageLike != null) {

            mapLike.put("message",messageLike);

            //将message中的content的中的JSONString形式 获取出来
            String content = HtmlUtils.htmlUnescape(messageLike.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            mapLike.put("user",userServiceImp.getUserById((int)data.get("userId")));
            mapLike.put("entityType",data.get("entityType"));
            mapLike.put("entityId",data.get("entityId"));
            mapLike.put("postId",data.get("postId"));

            int countsNotices = messageServiceImp.selectCountsNotices(user.getId(), TOPIC_LIKE);
            int noReadNotices = messageServiceImp.selectCountsNoReadNotices(user.getId(), TOPIC_LIKE);

            mapLike.put("countsNotices",(Integer)countsNotices);
            mapLike.put("noReadNotices",(Integer)noReadNotices);
        }



        //处理关注
        Message messageFollow = messageServiceImp.selectLatestNotice(user.getId(), TOPIC_FOLLOW);

        Map<String, Object> mapFollow = new HashMap<>();
        if (messageFollow != null) {

            mapFollow.put("message",messageFollow);

            //将message中的content的中的JSONString形式 获取出来
            String content = HtmlUtils.htmlUnescape(messageFollow.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            mapFollow.put("user",userServiceImp.getUserById((int)data.get("userId")));
            mapFollow.put("entityType",data.get("entityType"));
            mapFollow.put("entityId",data.get("entityId"));
            mapFollow.put("postId",data.get("postId"));

            int countsNotices = messageServiceImp.selectCountsNotices(user.getId(), TOPIC_FOLLOW);
            int noReadNotices = messageServiceImp.selectCountsNoReadNotices(user.getId(), TOPIC_FOLLOW);

            mapFollow.put("countsNotices",(Integer)countsNotices);
            mapFollow.put("noReadNotices",(Integer)noReadNotices);


            model.addAttribute("noReadNotices",(Integer)noReadNotices);

        }

        ArrayList<Map<String,Object>> noticeList = new ArrayList<>();


        noticeList.add(mapComment);
        noticeList.add(mapLike);
        noticeList.add(mapFollow);

        model.addAttribute("noticeList",noticeList);

        return "site/notice";
    }


    @RequestMapping(value = "/getNoticeDetail/{conversationId}",method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("conversationId") String conversationId,Model model,Page page){

        User user = hostHolder.getUser();

        page.setRows(messageServiceImp.selectCountsNotices(user.getId(),conversationId));
        page.setPath("/getNoticeDetail/"+conversationId);
        page.setLimit(10);

        List<Message> messageList = messageServiceImp.selectNoticesByConversationId(user.getId(), conversationId, page.getCurrent(), page.getLimit());

        ArrayList<Map<String,Object>> messageListVo = new ArrayList<>();

        if (messageListVo != null) {
            for (Message message : messageList) {
                Map<String, Object> messageMapVo = new HashMap<>();

                messageMapVo.put("message",message);

                String content = HtmlUtils.htmlUnescape(message.getContent());
                Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

                messageMapVo.put("user",userServiceImp.getUserById((int)data.get("userId")));
                messageMapVo.put("fromUser","系统通知");
                messageMapVo.put("topic",conversationId);
                messageMapVo.put("postId",data.get("postId"));

                messageListVo.add(messageMapVo);
            }
        }


        model.addAttribute("messageListVo",messageListVo);


        //更改信息的状态  将status = 0 更改为1
        List<Integer> ids = getUpdateStatusIds(messageList);
        if (ids.size() != 0) {
            messageServiceImp.updateStatus(ids);
        }
        return "site/notice-detail";
    }

}

